package com.wzxl.config.web;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;


/**
 * @version V1.0
 * @package com.wzxl.config.web
 * @description: TODO ( Servlet 工具类)
 * @date 2017-11-下午3:24
 */
public class Servlets {

    public static HttpServletRequest request = null;

    public static final Logger LOGGER = LoggerFactory.getLogger(Servlets.class);

    private static final String STATIC_RESOURCE = ".css,.js,.png,.jpg,.gif,.jpeg,.bmp,.ico,.swf,.psd,.htc,.htm,.html,.crx,.xpi,.exe,.ipa,.apk";

    private static final String URL_SUFFIX = ".html";

    private final static String[] STATIC_FILES = StringUtils.split(STATIC_RESOURCE, ",");


    public static HttpServletRequest getRequest() {
        try {
            if (null == request) {
                return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            }
        } catch (Exception ex) {
            LOGGER.error("Init httpServletRequest error, {}", ex.getMessage());
        }
        return request;
    }

    /**
     * 判断访问URI是否是静态文件请求
     *
     * @throws Exception
     */
    public static boolean isStaticFile(String uri) {
        if (STATIC_FILES == null) {
            try {
                throw new Exception("检测到“app.properties”中没有配置“web.staticFile”属性。配置示例：\n#静态文件后缀\n"
                        + "web.staticFile=.css,.js,.png,.jpg,.gif,.jpeg,.bmp,.ico,.swf,.psd,.htc,.crx,.xpi,.exe,.ipa,.apk");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return StringUtils.endsWithAny(uri, STATIC_FILES) && !StringUtils.endsWithAny(uri, URL_SUFFIX)
                && !StringUtils.endsWithAny(uri, ".jsp") && !StringUtils.endsWithAny(uri, ".java");
    }
}
